import React, { useState, useEffect } from 'react';
import UserLayout from '../../pages/user/UserLayout.js';
import axios from 'axios';
import {useNavigate } from 'react-router-dom';
import Toast from '../../components/Toast.js';
import PaginationComponent from '../network/NetworkHome/components/PaginationComponent.js';
import './upload.css';

const API_BASE_URL = 'http://117.72.106.234:8080/api';

// 创建axios实例
const resourceApi = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
resourceApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const ManageUploads = () => {
  const navigate = useNavigate();
  const [resources, setResources] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingResource, setEditingResource] = useState(null);
  const [categories, setCategories] = useState([]);
  const [toast, setToast] = useState({ show: false, message: '' });
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    categoryName: '',
    tags: '',
    price: 0,
    isFree: false,
    torrentFile: null,
    coverImage: null
  });

  useEffect(() => {
    fetchMyResources();
    fetchCategories();
  }, []);

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await resourceApi.get(`${API_BASE_URL}/resource/categories`);
      if (response.data.code === 200) {
        setCategories(response.data.data);
      }
    } catch (err) {
      showToast('获取分类失败');
    }
  };

  // 显示Toast消息
  const showToast = (message) => {
    setToast({ show: true, message });
  };

  // 关闭Toast
  const closeToast = () => {
    setToast({ show: false, message: '' });
  };

  // 获取用户上传的资源列表
  const fetchMyResources = async (page = 1, pageSize = 10) => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch(`${API_BASE_URL}/resource/my-resources?pageNum=${page}&pageSize=${pageSize}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      const data = await response.json();
      if (data.code === 200) {
        setResources(data.data.resources);
        setTotalPages(data.data.totalPages);
        setCurrentPage(data.data.pageNum);
      } else {
        setError('获取资源列表失败');
      }
    } catch (error) {
      setError('获取资源列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  // 处理分页变化
  const handlePaginationChange = (page, pageSize) => {
    fetchMyResources(page, pageSize);
  };

  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value, type, checked, files } = e.target;
    if (type === 'file') {
      setFormData(prev => ({ ...prev, [name]: files[0] }));
    } else if (type === 'checkbox') {
      setFormData(prev => ({ 
        ...prev, 
        [name]: checked,
        price: checked ? 0 : prev.price
      }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  // 创建资源
  const handleCreate = async () => {
    const formDataToSend = new FormData();
    formDataToSend.append('title', formData.title);
    formDataToSend.append('description', formData.description);
    formDataToSend.append('categoryName', formData.categoryName);
    formDataToSend.append('tags', JSON.stringify(formData.tags.split(',').map(tag => tag.trim())));
    formDataToSend.append('price', formData.price);
    formDataToSend.append('isFree', formData.isFree);
    formDataToSend.append('torrentFile', formData.torrentFile);
    if (formData.coverImage) {
      formDataToSend.append('coverImage', formData.coverImage);
    }

    try {
      const response = await fetch(`${API_BASE_URL}/resource/create`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: formDataToSend
      });
      const data = await response.json();
      if (data.code === 200) {
        showToast('资源创建成功！');
        setShowCreateForm(false);
        resetForm();
        fetchMyResources(currentPage);
      } else {
        showToast(data.message || '创建资源失败');
      }
    } catch (error) {
      showToast('创建资源失败，请重试');
    }
  };

  // 更新资源
  const handleUpdate = async () => {
    const formDataToSend = new FormData();
    formDataToSend.append('title', formData.title);
    formDataToSend.append('description', formData.description);
    formDataToSend.append('tags', JSON.stringify(formData.tags.split(',').map(tag => tag.trim())));
    formDataToSend.append('price', formData.price);
    formDataToSend.append('isFree', formData.isFree);
    if (formData.coverImage) {
      formDataToSend.append('coverImage', formData.coverImage);
    }

    try {
      const response = await fetch(`${API_BASE_URL}/resource/update/${editingResource.resourceId}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: formDataToSend
      });
      const data = await response.json();
      if (data.code === 200) {
        showToast('资源更新成功！');
        setEditingResource(null);
        resetForm();
        fetchMyResources(currentPage);
      } else {
        showToast(data.message || '更新资源失败');
      }
    } catch (error) {
      showToast('更新资源失败，请重试');
    }
  };

  // 删除资源
  const handleDelete = async (resourceId) => {
    if (!window.confirm('确定要删除这个资源吗？')) return;

    try {
      const response = await fetch(`${API_BASE_URL}/resource/${resourceId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      const data = await response.json();
      if (data.code === 200) {
        showToast('资源删除成功！');
        fetchMyResources(currentPage);
      } else {
        showToast(data.message || '删除资源失败');
      }
    } catch (error) {
      showToast('删除资源失败，请重试');
    }
  };

  // 编辑资源
  const handleEdit = (resource) => {
    setEditingResource(resource);
    setFormData({
      title: resource.title,
      description: resource.description || '',
      categoryName: resource.categoryName,
      tags: resource.tags.join(', '),
      price: resource.price,
      isFree: resource.isFree,
      torrentFile: null,
      coverImage: null
    });
    setShowCreateForm(false);
  };

  // 查看资源详情
  const handleViewDetail = (resourceId) => {
    // 导航到前端的资源详情页面，而不是API端点
    navigate(`/resource/detail/${resourceId}`);
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      title: '',
      description: '',
      categoryName: '',
      tags: '',
      price: 0,
      isFree: false,
      torrentFile: null,
      coverImage: null
    });
    setEditingResource(null);
  };

  // 渲染创建/编辑表单
  const renderForm = () => {
    if (!showCreateForm && !editingResource) return null;

    return (
      <div className="form-modal-overlay" onClick={() => {
        setShowCreateForm(false);
        setEditingResource(null);
        resetForm();
      }}>
        <div className="form-modal" onClick={(e) => e.stopPropagation()}>
          <div className="form-modal-header">
            <h3>{editingResource ? '编辑资源' : '创建新资源'}</h3>
            <button 
              className="close-btn" 
              onClick={() => {
                setShowCreateForm(false);
                setEditingResource(null);
                resetForm();
              }}
            >
              ×
            </button>
          </div>
          
          <div className="resource-form">
            <div className="form-group">
              <label className="form-label">标题 *</label>
              <input
                type="text"
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                required
                className="form-input"
                placeholder="请输入资源标题"
              />
            </div>

            <div className="form-group">
              <label className="form-label">描述</label>
              <textarea
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                rows="4"
                className="form-textarea"
                placeholder="请输入资源描述"
              />
            </div>

            {!editingResource && (
              <div className="form-group">
                <label className="form-label">分类 *</label>
                <select
                  name="categoryName"
                  value={formData.categoryName}
                  onChange={handleInputChange}
                  required
                  className="form-select"
                >
                  <option value="">选择分类</option>
                  {categories.map(category => (
                    <option key={category.categoryId} value={category.name}>
                      {category.icon} {category.name}
                    </option>
                  ))}
                </select>
              </div>
            )}

            <div className="form-group">
              <label className="form-label">标签</label>
              <input
                type="text"
                name="tags"
                value={formData.tags}
                onChange={handleInputChange}
                placeholder="用逗号分隔，如：动作, 科幻, 冒险"
                className="form-input"
              />
            </div>

            <div className="form-row">
              <div className="form-group checkbox-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    name="isFree"
                    checked={formData.isFree}
                    onChange={handleInputChange}
                    className="form-checkbox"
                  />
                  <span className="checkmark"></span>
                  免费资源
                </label>
              </div>

              {!formData.isFree && (
                <div className="form-group price-group">
                  <label className="form-label">价格 (积分)</label>
                  <input
                    type="number"
                    name="price"
                    value={formData.price}
                    onChange={handleInputChange}
                    min="0"
                    className="form-input price-input"
                  />
                </div>
              )}
            </div>

            {!editingResource && (
              <div className="form-group">
                <label className="form-label">种子文件 *</label>
                <input
                  type="file"
                  name="torrentFile"
                  onChange={handleInputChange}
                  accept=".torrent"
                  required
                  className="form-file"
                />
              </div>
            )}

            <div className="form-group">
              <label className="form-label">封面图片</label>
              <input
                type="file"
                name="coverImage"
                onChange={handleInputChange}
                accept="image/*"
                className="form-file"
              />
            </div>

            <div className="form-actions">
              <button 
                type="button" 
                onClick={editingResource ? handleUpdate : handleCreate}
                className="submit-btn"
              >
                {editingResource ? '更新资源' : '创建资源'}
              </button>
              <button
                type="button"
                onClick={() => {
                  setShowCreateForm(false);
                  setEditingResource(null);
                  resetForm();
                }}
                className="cancel-btn"
              >
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  };
  
  // 渲染资源列表
  const renderResourceList = () => {
    if (resources.length === 0) {
      return (
        <div className="empty-state">
          <div className="empty-icon">📁</div>
          <p>您还没有上传任何资源</p>
          <button 
            className="create-first-btn"
            onClick={() => {
              setShowCreateForm(true);
              setEditingResource(null);
              resetForm();
            }}
          >
            创建第一个资源
          </button>
        </div>
      );
    }

    return (
      <div className="resources-list">
      {resources.map(resource => (
        <div 
          key={resource.resourceId} 
          className={`resource-item ${resource.status === 'removed' ? 'removed-item' : ''}`}
        >
          {resource.status === 'removed' && (
            <div className="removed-badge">已移除</div>
          )}
          
          {resource.isFree && (
            <span className="free-badge">免费</span>
          )}
          
          <div className="resource-cover">
            <img 
              src={resource.coverUrl || '/default-cover.jpg'} 
              alt={resource.title}
              onError={(e) => { e.target.src = '/default-cover.jpg' }}
            />
          </div>
          
          <div className="resource-info">
            <h3 className="resource-title">
              {resource.title.length > 20 ? resource.title.substring(0, 20) + '...' : resource.title}
              <button 
                onClick={() => handleViewDetail(resource.resourceId)}
                className="title-link"
                style={{ 
                  background: 'none', 
                  border: 'none', 
                  color: 'inherit', 
                  textDecoration: 'underline',
                  cursor: 'pointer',
                  fontSize: 'inherit',
                  fontWeight: 'inherit',
                  padding: 0
                }}
              >
                
              </button>
            </h3>
            
            <div className="resource-meta">
              <span className="category">{resource.categoryName}</span>
              {!resource.isFree && (
                <span className="price">
                  <span className="price-badge">{resource.price} 积分</span>
                </span>
              )}
            </div>
            
            <div className="resource-tags">
              {resource.tags.slice(0, 3).map((tag, index) => (
                <span key={index} className="tag">{tag}</span>
              ))}
              {resource.tags.length > 3 && (
                <span className="tag more">+{resource.tags.length - 3}</span>
              )}
            </div>
            
            <div className="resource-stats">
              <div className="stat">
                <span className="stat-icon">👍</span>
                <span className="stat-value">{resource.likesCount}</span>
              </div>
              <div className="stat">
                <span className="stat-icon">⬇️</span>
                <span className="stat-value">{resource.torrentDownloadsCount}</span>
              </div>
            </div>
          </div>
          
          <div className="resource-actions">
            <button
              onClick={() => handleEdit(resource)}
              className="action-btn edit-btn"
              disabled={resource.status === 'removed'}
            >
              <span className="btn-icon">✏️</span>
              编辑
            </button>
            <button
              onClick={() => handleDelete(resource.resourceId)}
              className="action-btn delete-btn"
              disabled={resource.status === 'removed'}
            >
              <span className="btn-icon">🗑️</span>
              删除
            </button>
            <button 
              onClick={() => handleViewDetail(resource.resourceId)}
              className="action-btn detail-btn"
              disabled={resource.status === 'removed'}
            >
              <span className="btn-icon">👁️</span>
              查看
            </button>
          </div>
        </div>
      ))}
    </div>
  );
};
  if (loading) {
    return (
      <UserLayout>
        <div className="manage-uploads-container">
          <div className="loading-container">
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        </div>
      </UserLayout>
    );
  }

  return (
    <UserLayout>
      <div className="manage-uploads-container">
        <div className="page-header">
          <div className="header-content">
            <h1 className="page-title">管理上传</h1>
            <p className="page-subtitle">管理您上传的所有资源</p>
          </div>
          
          <button 
            className="create-btn"
            onClick={() => {
              setShowCreateForm(true);
              setEditingResource(null);
              resetForm();
            }}
          >
            <span className="btn-icon">+</span>
            创建新资源
          </button>
        </div>

        {error && (
          <div className="error-message">
            <span className="error-icon">⚠️</span>
            {error}
          </div>
        )}

        <div className="content-section">
          {renderResourceList()}
          
          {/* 分页 */}
          {totalPages > 1 && (
            <div className="pagination-container">
              <PaginationComponent
                current={currentPage}
                pageSize={10}
                total={totalPages * 10}
                onChange={handlePaginationChange}
              />
            </div>
          )}
        </div>
        
        {renderForm()}
        
        {/* Toast组件 */}
        {toast.show && (
          <Toast 
            message={toast.message} 
            onClose={closeToast}
          />
        )}
      </div>
    </UserLayout>
  );
};

export default ManageUploads;